package com.xdog.web3.controller.balance;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSONObject;
import com.xdog.common.core.domain.R;
import com.xdog.web3.domain.balance.SpecificTokenBalanceRequest;
import com.xdog.web3.domain.balance.TokenBalanceQuery;
import com.xdog.web3.domain.balance.TotalValueQuery;
import com.xdog.web3.exception.Web3ApiException;
import com.xdog.web3.service.IBalanceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * 余额控制器
 */
@Tag(name = "余额", description = "余额相关接口")
@RestController
@RequestMapping("/web3/balance")
public class BalanceController {

    @Resource
    private IBalanceService balanceService;

    /**
     * 获取地址下全量代币和 Defi 资产总余额
     */
    @Operation(summary = "获取地址总估值", description = "获取地址下全量代币和 Defi 资产总余额")
    @GetMapping("/total-value")
    @SaIgnore
    public R<JSONObject> getTotalValueByAddress(TotalValueQuery query) {
        try {
            JSONObject result = balanceService.getTotalValueByAddress(query);
            return R.ok(result);
        } catch (Web3ApiException e) {
            return R.fail(e.getHttpStatus(), "API错误: " + e.getMessage());
        } catch (Exception e) {
            return R.fail("获取地址总估值失败: " + e.getMessage());
        }
    }

    /**
     * 查询地址持有的多个链或指定链的代币余额列表
     */
    @Operation(summary = "获取资产明细", description = "查询地址持有的多个链或指定链的代币余额列表")
    @GetMapping("/token-balances")
    @SaIgnore
    public R<JSONObject> getAllTokenBalancesByAddress(TokenBalanceQuery query) {
        try {
            JSONObject result = balanceService.getAllTokenBalancesByAddress(query);
            return R.ok(result);
        } catch (Web3ApiException e) {
            return R.fail(e.getHttpStatus(), "API错误: " + e.getMessage());
        } catch (Exception e) {
            return R.fail("获取资产明细失败: " + e.getMessage());
        }
    }

    /**
     * 查询地址下指定代币的余额
     */
    @Operation(summary = "获取特定代币余额", description = "查询地址下指定代币的余额")
    @PostMapping("/specific-token-balances")
    @SaIgnore
    public R<JSONObject> getTokenBalancesByAddress(@RequestBody SpecificTokenBalanceRequest request) {
        try {
            JSONObject result = balanceService.getTokenBalancesByAddress(request);
            return R.ok(result);
        } catch (Web3ApiException e) {
            return R.fail(e.getHttpStatus(), "API错误: " + e.getMessage());
        } catch (Exception e) {
            return R.fail("获取特定代币余额失败: " + e.getMessage());
        }
    }
}
